<template>
  <base-breadcrumb
    v-loading="loadingState.loading"
    :breadcrumb="!isAudit"
  >
    <a-card>
      <title-name title="维保信息" />
      <custom-form
        ref="baseForm"
        :rules="rules"
        :is-validate="true"
        :form-list="formList"
        :form="formInfo"
        :edit-model="''"
        :is-emit="false"
      />
      <a-form-model
        ref="baseForm"
        :model="formInfo"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-row type="flex">
          <a-col :span="8">
            <a-form-model-item label="维保发起时间">
              <BaseInput
                v-model="formInfo.maintenanceTime"
                disabled
              />
            </a-form-model-item>
            <a-form-model-item label="维保事项">
              <BaseInput
                v-model="formInfo.maintenanceMatter"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="16">
            <a-form-model-item
              label="维保诉求"
              class="basehei"
            >
              <BaseTextarea
                v-model="formInfo.maintenanceAppeal"
                :auto-size="{ minRows: 4, maxRows: 5 }"
                disabled
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card>
      <title-name title="维保方案信息" />
      <custom-form
        ref="planForm"
        :rules="rules"
        :is-validate="true"
        :form-list="formList2"
        :form="formInfo"
        :edit-model="''"
        :is-emit="false"
      />
    </a-card>

    <a-card>
      <title-name title="相关附件" />
      <UploadTableNew
        ref="uploadTable"
        :mode="mode"
        :disabled=" !editable"
        :init-file-list="fileList"
        :need-page="false"
        :business-code="'CUSTOMER04'"
        :use-multi-delete="true"
        :use-multi-export="true"
      />
    </a-card>

    <div v-if="!isConsultation" class="tool-btns page-btn-right-top">
      <a-button
        v-if="editable"
        class="ml12"
        type="primary"
        :disabled="loadingState.SUBMITTED"
        :loading="loadingState.DRAFT"
        @click="handleSubmit('DRAFT')"
      >
        保存草稿
      </a-button>
      <a-button
        v-if="editable"
        class="ml12"
        type="primary"
        :disabled="loadingState.DRAFT"
        :loading="loadingState.SUBMITTED"
        @click="handleSubmit('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button
        class="ml12"
        type="default"
        @click="$close"
      >
        关闭
      </a-button>
    </div>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import { getMaintenancePlanDetial, editMaintenancePlan } from '@/api/complaint/maintenanceplan'

export default {
  name: 'a' + Date.now(),
  components: {
    ASelectOrgPeople
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      pageType: this.$route.query.type,
      mode: this.$route.query.type === 'add' ? 'add' : 'edit',
      loadingState: {
        loading: false,
        DRAFT: false,
        SUBMITTED: false,
      },
        fileList:[],
      formInfo: {
      },
      rules: {
        maintenanceFee: { required: true, message: '请输入预计维保金额（万元）', trigger: 'blur'},
        implementSubOrg: { required: true, message: '请输入实施分包单位', trigger: 'blur'},
        responsibleId: { required: true, message: '请选择负责人', trigger: 'change'},
        planCompletedTime: { required: true, message: '请选择维修计划完成时间', trigger: 'blur'},
        implementContent: { required: true, message: '请输入实施维修内容', trigger: 'blur'},
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    formList() {
      return [
        {
          label: '项目名称',
          keyName: 'projectName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '维保发起人',
          keyName: 'maintenancePeople',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '维保发起周期',
          keyName: 'maintenanceCycle',
          type: 'BaseInput',
          disabled: true
        },
        // {
        //   label: '维保发起时间',
        //   keyName: 'maintenanceTime',
        //   type: 'BaseInput',
        //   disabled: true
        // },
        // {
        //   label: '维保诉求',
        //   keyName: 'maintenanceAppeal',
        //   type: 'BaseTextarea',
        //   span: 16,
        //   disabled: true
        // },
        // {
        //   label: '维保事项',
        //   keyName: 'maintenanceMatter',
        //   type: 'BaseInput',
        //   disabled: true
        // },
      ]
    },
    formList2() {
      return [
        {
          label: '维保方案编号',
          keyName: 'maintenancePlanCode',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '维保方案状态',
          keyName: 'maintenancePlanStatus',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '预计维保金额（万元）',
          keyName: 'maintenanceFee',
          type: 'BaseInputNumber',
            precision: 2,
          attrs: {
          },
          disabled: !this.editable,
        },
        {
          label: '实施分包单位',
          keyName: 'implementSubOrg',
          type: 'BaseInput',
          disabled: !this.editable,
        },
        {
          label: '负责人',
          keyName: 'responsibleId',
          viewName: 'responsible',
          type: ASelectOrgPeople,
          attrs: {
            customRender: null,
            customName: (e) => {
              let str = e.name;
              if (e.phone || e.phoneNum) {
                str = str + ' ' + e.phone || e.phoneNum
              }
              return str
            }
          },
          disabled: !this.editable,
          onSelectChange: (e) => {
            this.$set(this.formInfo, 'responsible', e.name || '')
          }
        },
        {
          label: '维修计划完成时间',
          keyName: 'planCompletedTime',
          type: 'a-date-picker',
          disabled: !this.editable,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            format: 'YYYY-MM-DD'
          }
        },
        {
          label: '实施维修内容',
          keyName: 'implementContent',
          type: 'BaseTextarea',
          span: 24,
          disabled: !this.editable,
        },
      ]
    },
    editable() {
      return this.pageType == 'add' || this.pageType == 'edit'
    },
    // pageType() {
    //   return this.$route.query.type
    // }
  },
  watch: {
    isAudit: { // 是否作为审批详情
      immediate: true,
      handler (val) {
        if (val) {
          this.pageType = 'look'
        }
      }
    },
  },
 async created () {
   //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('complaint_maintenance_plan');
 },
  mounted() {
    this.getDetail();
  },
  methods: {
    getDetail () {
      this.loadingState.loading = true
      getMaintenancePlanDetial({id: this.$route.query.id}).then((res) => {
        this.loadingState.loading = false
        if (res.code == 0) {
          this.formInfo = res.data
          this.fileList = res.data.fileList
        }
      }).catch(() => {
        this.loadingState.loading = false
      })
    },
    handleSubmit(status) {
      let that = this
      if (status == 'SUBMITTED') {
        this.$refs.planForm.validate((valid) => {
          if (!valid) return;
          this.submit(status)
        })
      } else {
        this.submit(status)
      }
    },
    submit (status) {
      this.setProcessConfig = null; 
      let param = { ...this.formInfo,fileList:this.fileList };
      delete param.maintenanceTimeBegin;
      delete param.maintenanceTimeEnd;
      delete param.planCompletedTimeBegin;
      delete param.planCompletedTimeEnd;
      delete param.projectIdList;
      param.status = status == 'SUBMITTED' ? 1 : 0;
      let msg = status == 'SUBMITTED' ? '提交' : '保存';
      // console.log(this.formInfo)
      // console.log(param)
      // return new Promise((resove, reject) => {
      //   setTimeout(() => {
      //     console.log('end')
      //     resove('1111')
      //   }, 1000)
      // }).then((res) => {
      //   console.log(res)
      // })

    this.submitApprovalConfirm(this.processConfig, (flag)=>{
      if(!flag) {
        this.loadingState[status] = false
        return
      }
      this.loadingState[status] = true;
      return editMaintenancePlan(param).then((res) => {
        this.loadingState[status] = false
        if (res.code == 0 || res.data.code == 0) {
          this.$message.success(`${msg}成功！`);
          if(status =='SUBMITTED') {
            //提交时，返回id
                this.businessId = res.data?.id;
                this.setProcessConfig = this.processConfig;
                return
            }else{
              this.$close();
          }
        }
      }).catch(() => {
        this.loadingState[status] = false
      })
           })
    },
  }
}
</script>
<style lang="less" scoped>
  // .basehei /deep/ textarea {
  //   height: 100px !important;
  // }
</style>